<template>
  <div class="login-container">
    <!-- 背景装饰层（修复：简化背景逻辑，确保显示） -->
    <div class="login-bg"></div>

    <!-- 登录主体卡片（修复：确保居中，优化动画初始值） -->
    <el-form 
      ref="loginRef" 
      :model="loginForm" 
      :rules="loginRules" 
      class="login-card"
      @keyup.enter="handleLogin"
    >
      <!-- 标题区（保留原逻辑） -->
      <div class="login-header">
        <div class="login-logo">
          <el-icon class="icon-ai" color="#00C48C"><svg viewBox="0 0 24 24" width="28" height="28"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg></el-icon>
        </div>
        <h3 class="login-title">AI集成演示系统</h3>
        <p class="login-subtitle">智能高效 · 集成创新</p>
      </div>

      <!-- 账号输入框（保留原逻辑） -->
      <el-form-item prop="username" class="login-form-item">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输入账号"
          class="login-input"
        >
          <template #prefix>
            <el-icon class="input-icon"><svg viewBox="0 0 24 24" width="18" height="18"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2-1.1 2-2 2c-.55 0-1 .45-1 1v1h2v-1c2.21 0 4-1.79 4-4s-1.79-4-4-4zm-1 9h2v2h-2z"/></svg></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码输入框（保留原逻辑） -->
      <el-form-item prop="password" class="login-form-item">
        <el-input
          v-model="loginForm.password"
          :type="showPwd ? 'text' : 'password'"
          size="large"
          auto-complete="off"
          placeholder="请输入密码"
          class="login-input"
          @keyup.enter="handleLogin"
        >
          <template #prefix>
            <el-icon class="input-icon"><svg viewBox="0 0 24 24" width="18" height="18"><path d="M12 16c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v8c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 16 6.7 13H5c0 3.41 2.72 6.23 6 6.72V21h2v-1.28c3.28-.48 6-3.3 6-6.72h-1.7z"/></svg></el-icon>
          </template>
          <template #suffix>
            <el-icon 
              class="input-icon cursor-pointer" 
              @click="showPwd = !showPwd"
              color="#909399"
            >
              <svg v-if="showPwd" viewBox="0 0 24 24" width="18" height="18"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>
              <svg v-else viewBox="0 0 24 24" width="18" height="18"><path d="M12 7c2.76 0 5 2.24 5 5 0 .64-.1 1.26-.27 1.84l1.49 1.49C19.54 14.82 20 13.45 20 12c0-4.42-3.58-8-8-8-1.45 0-2.82.46-4.01 1.23l1.49 1.49C8.74 7.1 9.36 7 10 7c1.66 0 3 1.34 3 3zm-3.71 9.37l-1.32-1.32c-.37.22-.78.35-1.21.41v1.77c0 .55.45 1 1 1h1.77c.43-.06.84-.19 1.21-.41zM12 19c-1.66 0-3-1.34-3-3 0-.64.1-1.26.27-1.84l-1.49-1.49C2.46 13.18 2 14.55 2 16c0 4.42 3.58 8 8 8 1.45 0 2.82-.46 4.01-1.23l-1.49-1.49C13.26 18.9 12.64 19 12 19zm5.71-4.37l1.32 1.32c.37-.22.78-.35 1.21-.41h-1.77c-.43.06-.84.19-1.21.41zM14.3 14.95l1.27-1.27c.2-.2.51-.2.71 0 .2.2.2.51 0 .71l-1.27 1.27c-.2.2-.51.2-.71 0-.2-.2-.2-.51 0-.71z"/></svg>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 验证码（保留原逻辑） -->
      <el-form-item prop="code" v-if="captchaEnabled" class="login-form-item">
        <div class="verify-code-wrap">
          <el-input
            v-model="loginForm.code"
            size="large"
            auto-complete="off"
            placeholder="请输入验证码"
            class="login-input verify-code-input"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <el-icon class="input-icon"><svg viewBox="0 0 24 24" width="18" height="18"><path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zm0 16c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7zm1-11h-2v2H9v2h2v2h2v-2h2v-2h-2V8z"/></svg></el-icon>
            </template>
          </el-input>
          <div class="verify-code-img-wrap" @click="getCode">
            <img 
              :src="codeUrl" 
              class="verify-code-img"
              :class="{ 'verify-code-refresh': isRefreshing }"
              alt="验证码"
            >
            <el-icon class="verify-code-loading" v-if="isRefreshing">
              <svg viewBox="0 0 24 24" width="20" height="20" color="#165DFF"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/></svg>
            </el-icon>
          </div>
        </div>
      </el-form-item>

      <!-- 记住密码+注册链接（保留原逻辑） -->
      <div class="login-option">
        <el-checkbox 
          v-model="loginForm.rememberMe" 
          class="remember-me"
          :style="{ '--color-primary': '#165DFF', '--color-primary-light': '#E8F3FF' }"
        >
          记住密码
        </el-checkbox>
        <router-link 
          class="register-link" 
          :to="'/register'" 
          v-if="register"
        >
          立即注册 →
        </router-link>
      </div>

      <!-- 登录按钮（保留原逻辑） -->
      <el-form-item class="login-btn-item">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          class="login-btn"
          @click.prevent="handleLogin"
        >
          <template #default>
            <span v-if="!loading">智能登录</span>
            <span v-else class="loading-text">登录中...</span>
          </template>
          <template #loading>
            <svg class="loading-icon" viewBox="0 0 24 24" width="20" height="20">
              <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/>
            </svg>
          </template>
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 底部版权（修复：确保在底部显示） -->
    <div class="login-footer">
      <span class="copyright">Copyright © 2018-2024 AI集成演示系统 | 智能驱动 · 高效协同</span>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user';
import { useRoute, useRouter } from "vue-router";
import { getCurrentInstance } from "vue";

// 状态管理与路由（保留原逻辑）
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 登录表单状态（保留原逻辑）
const loginForm = ref({
  username: "yuzx",
  password: "123456",
  rememberMe: false,
  code: "",
  uuid: ""
});

// 新增：密码显示/隐藏状态、验证码刷新动画状态（保留原逻辑）
const showPwd = ref(false);
const isRefreshing = ref(false);

// 表单规则（保留原逻辑）
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的登录账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的账号密码" }],
  code: [{ required: true, trigger: "change", message: "请输入图形验证码" }]
};

// 原有状态保留（保留原逻辑）
const codeUrl = ref("");
const loading = ref(false);
const captchaEnabled = ref(true);
const register = ref(false);
const redirect = ref(undefined);

// 监听路由变化（保留原逻辑）
watch(route, (newRoute) => {
  redirect.value = newRoute.query?.redirect;
}, { immediate: true });

// 登录逻辑（保留原逻辑）
const handleLogin = () => {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 记住密码逻辑（保留原逻辑）
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用登录接口（保留原逻辑）
      userStore.login(loginForm.value).then(() => {
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") acc[cur] = query[cur];
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
        // 验证码刷新（保留原逻辑）
        if (captchaEnabled.value) getCode();
      });
    }
  });
};

// 验证码获取（保留原逻辑）
const getCode = () => {
  isRefreshing.value = true;
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled ?? true;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
    setTimeout(() => isRefreshing.value = false, 300);
  });
};

// Cookie读取（保留原逻辑）
const getCookie = () => {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username ?? loginForm.value.username,
    password: password ? decrypt(password) : loginForm.value.password,
    rememberMe: rememberMe ? Boolean(rememberMe) : false
  };
};

// 页面加载时执行（保留原逻辑）
onMounted(() => {
  getCode();
  getCookie();
  // 卡片渐入动画（修复：确保动画不影响居中）
  setTimeout(() => {
    document.querySelector(".login-card")?.classList.add("login-card-fade-in");
  }, 100);
});
</script>

<style lang='scss' scoped>
// 第一步：修复全屏高度（确保登录容器能撑满屏幕）
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

// 全局变量（保留原逻辑）
$color-primary: #165DFF;
$color-primary-light: #E8F3FF;
$color-secondary: #00C48C;
$color-neutral-dark: #1E293B;
$color-neutral-light: #F8FAFC;
$shadow-tech: 0 8px 32px rgba(22, 93, 255, 0.15);

// 第二步：修复登录容器居中（用flex实现水平+垂直居中）
.login-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  // 关键：水平+垂直居中
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0; // 上下留边距，避免小屏幕溢出
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  // 关键：正确引用图片路径（@ 指向 src 目录）
  background-image: url("../assets/images/login-background.jpg"); 
  background-size: cover; // 图片覆盖整个容器
  background-repeat: no-repeat; // 不重复
  background-position: center; // 图片居中
  z-index: 0; // 确保在最底层
  opacity: 0.8; // 透明度（可根据需求调整）
}

// 第四步：修复登录卡片居中（优化初始状态，避免偏移）
.login-card {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 420px;
  padding: 36px 32px 24px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: $shadow-tech;
  backdrop-filter: blur(8px);
  border: 1px solid rgba(22, 93, 255, 0.1);
  // 修复：初始状态无偏移，动画仅控制透明度
  transform: translateY(0);
  opacity: 0;
  transition: opacity 0.6s cubic-bezier(0.16, 1, 0.3, 1);

  // 渐入动画（仅控制透明度，不影响居中）
  &.login-card-fade-in {
    opacity: 1;
  }
}

// 标题区（保留原逻辑）
.login-header {
  text-align: center;
  margin-bottom: 32px;

  .login-logo {
    width: 56px;
    height: 56px;
    margin: 0 auto 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: $color-primary-light;
    border-radius: 50%;
  }

  .login-title {
    font-size: 22px;
    font-weight: 600;
    color: $color-neutral-dark;
    margin: 0 0 8px;
  }

  .login-subtitle {
    font-size: 14px;
    color: #64748B;
    margin: 0;
  }
}

// 表单项目通用样式（保留原逻辑）
.login-form-item {
  margin-bottom: 20px;
}

// 输入框（保留原逻辑）
.login-input {
  height: 46px;
  border-radius: 8px;
  border-color: #E2E8F0;
  transition: all 0.3s;

  &:focus-within {
    border-color: $color-primary;
    box-shadow: 0 0 0 3px $color-primary-light;
  }

  input {
    height: 46px;
    font-size: 14px;
    color: $color-neutral-dark;
  }
}

// 输入框图标（保留原逻辑）
.input-icon {
  color: #94A3B8;
  transition: color 0.3s;

  .login-input:focus-within & {
    color: $color-primary;
  }

  &.cursor-pointer {
    cursor: pointer;
    &:hover {
      color: $color-primary;
    }
  }
}

// 验证码容器（保留原逻辑）
.verify-code-wrap {
  display: flex;
  gap: 12px;
  align-items: center;
}

.verify-code-input {
  flex: 1;
}

// 验证码图片容器（保留原逻辑）
.verify-code-img-wrap {
  width: 120px;
  height: 46px;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: $color-neutral-light;
  cursor: pointer;

  .verify-code-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: all 0.3s;

    &.verify-code-refresh {
      transform: rotate(10deg) scale(0.95);
      opacity: 0.6;
    }
  }

  .verify-code-loading {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.8);
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s;

    .isRefreshing & {
      opacity: 1;
      pointer-events: auto;
    }
  }
}

// 记住密码+注册链接（保留原逻辑）
.login-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 28px;
  font-size: 13px;

  .remember-me {
    color: #64748B;
    cursor: pointer;

    .el-checkbox__inner {
      border-radius: 4px;
      border-color: #CBD5E1;
      transition: all 0.3s;

      &:checked {
        background-color: var(--color-primary);
        border-color: var(--color-primary);
      }

      &:hover {
        border-color: var(--color-primary);
      }
    }

    .el-checkbox__label {
      transition: color 0.3s;
    }

    &:hover .el-checkbox__label {
      color: var(--color-primary);
    }
  }

  .register-link {
    color: $color-primary;
    text-decoration: none;
    transition: all 0.3s;

    &:hover {
      color: #0A4ADB;
      text-decoration: underline;
    }
  }
}

// 登录按钮（保留原逻辑）
.login-btn-item {
  margin-bottom: 16px;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background-color: $color-primary;
  border-color: $color-primary;
  transition: all 0.3s;

  &:hover {
    background-color: #0A4ADB;
    border-color: #0A4ADB;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(22, 93, 255, 0.3);
  }

  &:not(.is-loading):after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.1);
    transform: scale(0);
    opacity: 0;
    transition: transform 0.6s, opacity 0.6s;
  }

  &:not(.is-loading):hover:after {
    transform: scale(2);
    opacity: 1;
  }

  .loading-text {
    margin-left: 8px;
  }

  .loading-icon {
    animation: rotate 1.5s linear infinite;
  }
}

// 加载图标旋转动画（保留原逻辑）
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 第五步：修复底部版权居中（确保在屏幕底部）
.login-footer {
  position: absolute;
  bottom: 20px;
  left: 0;
  width: 100%;
  z-index: 2;
  text-align: center;

  .copyright {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.7);
    letter-spacing: 0.5px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  }
}

// 响应式适配（保留原逻辑，确保小屏幕居中）
@media (max-width: 480px) {
  .login-card {
    max-width: 90%;
    padding: 28px 24px 16px;
  }

  .verify-code-img-wrap {
    width: 100px;
  }

  .login-footer {
    bottom: 15px;

    .copyright {
      font-size: 11px;
    }
  }
}
</style>